package com.zyht.bank.manage.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.wx.core.process.WxApi;
import com.wx.entity.SysWxuser;
import com.wx.entity.WxTemplatePush;
import com.wx.message.template.Content;
import com.wx.message.template.MessageTemplate;
import com.wx.service.SysWxTokenService;
import com.wx.service.SysWxuserService;
import com.wx.service.WxTemplatePushService;
import com.wx.util.HttpClientUtil;
import com.wx.util.JsonUtil;
import com.wx.util.StringUtils;
import com.zyht.bank.entity.AxdCustInfo;
import com.zyht.bank.entity.AxdCustInfoExample;
import com.zyht.bank.entity.AxdCustInfoExample.Criteria;
import com.zyht.bank.entity.AxdCustLoan;
import com.zyht.bank.entity.AxdCustLoanExample;
import com.zyht.bank.entity.AxdOrgInfo;
import com.zyht.bank.entity.AxdOrgInfoExample;
import com.zyht.bank.enums.BankServiceMsgEnum;
import com.zyht.bank.enums.TemplateEnum;
import com.zyht.bank.manage.vo.CustInfoMsg;
import com.zyht.bank.manage.vo.OrgCodeVo;
import com.zyht.bank.manage.vo.OrgInfoVO;
import com.zyht.bank.model.LoanApplyMessage;
import com.zyht.bank.service.AxdCustInfoService;
import com.zyht.bank.service.AxdCustLoanService;
import com.zyht.bank.service.AxdOrgInfoService;
import com.zyht.common.AbsManageBaseController;
import com.zyht.common.bean.PropertiesUtilBean.PropertiesUtils;
import com.zyht.common.intercepter.Token;
import com.zyht.common.util.DateUtils;
import com.zyht.common.util.Page;

/**
* <p>Title:客户绑定信息后台管理 </p>
* <p>Description: </p>
* <p>Company: </p> 
* @author xgx
* @date 2017年6月30日
*/
@Controller
@RequestMapping("admin/customer")
public class AdminCoustomerController extends AbsManageBaseController{
	
	@Resource
	private AxdCustInfoService axdCustInfoService;
	
	@Resource
	private AxdCustLoanService axdCustLoanService;
	@Resource
	private WxTemplatePushService wxTemplatePushService;
	@Resource
	private AxdOrgInfoService axdOrgInfoService;
	@Resource
	private SysWxuserService sysWxuserService;
	@Resource
	private SysWxTokenService sysWxTokenService;
	@Value("#{propertiesReader[globle_default_wxid]}")
	private  String wxId;
	
	@RequestMapping("/index")
	public String index(@RequestParam(required=false) String custName,
            @RequestParam(required=false) String custIdNum,
			  @RequestParam(required=false) String custPhone,
			  @RequestParam(required=false) String code,
  			  @RequestParam(required=false,defaultValue="0") String status,
  			  Integer currentPage,Model model,HttpServletRequest request){
		//获取用户是什么权限
		/*HttpSession session = request.getSession();
		SysUser sysUser = (SysUser) session.getAttribute(sessionUserKey);
		Integer orgId = sysUser.getOrgId();
		AxdOrgInfo axdOrgInfo = axdOrgInfoService.findOneById(orgId);
		if(null==axdOrgInfo){
			model.addAttribute("msg","此用户无权访问");
			model.addAttribute("redirect","admin/index");
			return "message";
		}
		Integer orgLevel = axdOrgInfo.getOrgLevel();*/
		
		AxdCustInfoExample example=new AxdCustInfoExample();
		Criteria criteria = example.createCriteria();
		if(!status.equals("4")){
			criteria.andExamineStatusEqualTo(status);
		}
		if(StringUtils.isNotEmpty(custName)){
			  criteria.andCustNameLike("%"+custName+"%");
		 }
		if(StringUtils.isNotEmpty(custIdNum)){
			criteria.andCustIdNumEqualTo(custIdNum);
		}
		if(StringUtils.isNotEmpty(custPhone)){
			criteria.andCustPhoneEqualTo(custPhone);
		}
		//判断网点
		if(StringUtils.isEmpty(code)){
			/*List<String> listCode=null;
			if(orgLevel==2){
				listCode=axdOrgInfoService.getOrgCodes(axdOrgInfo.getOrgCode());
				criteria.andLoanOrgCodeIn(listCode);
			}
			if(orgLevel==3){
				code=axdOrgInfo.getOrgCode();
				criteria.andLoanOrgCodeEqualTo(code);
			}*/
		}else{
			OrgCodeVo axdOrgInfo = axdOrgInfoService.findOneByOrgCode(code);
			if(axdOrgInfo.getOrgLevel()==3){
				criteria.andLoanOrgCodeEqualTo(code);
			}
			if(axdOrgInfo.getOrgLevel()==2){
				List<String> findOrgCodes = axdOrgInfoService.findOrgCodes(code);
				criteria.andLoanOrgCodeIn(findOrgCodes);
			}
		}
		
		int total=axdCustInfoService.count(example);
		
		if(null==currentPage || currentPage==0){
			currentPage=1;
		}
		
		String pageSizeStr = PropertiesUtils.getConfig("paganation_page_size");
		int pageSize = Integer.valueOf(pageSizeStr);
		Page<AxdCustInfo> page = new Page<AxdCustInfo>(total,currentPage,pageSize);
		PageHelper.startPage(currentPage, pageSize);
		List<AxdCustInfo> list = axdCustInfoService.list(example);
		for(AxdCustInfo axdCustInfo:list){
			OrgCodeVo axdOrgInfo = axdOrgInfoService.findOneByOrgCode(axdCustInfo.getLoanOrgCode());
			if(null!=axdOrgInfo&&axdOrgInfo.getOrgLevel()==3){
				axdCustInfo.setSubBranch(axdOrgInfo.getName());
				if(StringUtils.isNotEmpty(axdOrgInfo.getPcode())){
					OrgCodeVo axdOrgInfo2 = axdOrgInfoService.findOneByOrgCode(axdOrgInfo.getPcode());
					axdCustInfo.setOrgBranch(axdOrgInfo2.getName());
				}
				
			}
			if(null!=axdOrgInfo&&axdOrgInfo.getOrgLevel()==2){
				axdCustInfo.setOrgBranch(axdOrgInfo.getName());
			}
		}
		page.setRecordList(list);
	    model.addAttribute("page",page);
	    model.addAttribute("custName",custName);
	    model.addAttribute("custIdNum",custIdNum);
	    model.addAttribute("status",status);
	    model.addAttribute("custPhone",custPhone);
	    if(null!=code){
	    	AxdOrgInfoExample examples=new AxdOrgInfoExample();
			examples.createCriteria().andOrgCodeEqualTo(code);
			List<AxdOrgInfo> lists = axdOrgInfoService.list(examples);
			model.addAttribute("orgInfo",lists.get(0));
	    }
	   /* model.addAttribute("orgLevel",orgLevel);*/
		return "/banks/manage/custinfo/index";
	}
	
	@RequestMapping("/check")
	@Token(save=true)
	public String check(HttpServletRequest request,Model model){
		String parameter = request.getParameter("custInfoId");
		AxdCustInfo axdCustInfo = axdCustInfoService.findOneById(Integer.valueOf(parameter));
		AxdCustLoanExample example= new AxdCustLoanExample();
		example.createCriteria().andCustIdNumEqualTo(axdCustInfo.getCustIdNum()).andIsDelEqualTo("0");
		List<AxdCustLoan> list = axdCustLoanService.list(example);
		if(list.size()<1){
			model.addAttribute("idNumFlag", false);
			example.createCriteria().andCustPhoneEqualTo(axdCustInfo.getCustPhone()).andIsDelEqualTo("0");;
			List<AxdCustLoan> list1 = axdCustLoanService.list(example);
			if(list1.size()<1){
				model.addAttribute("phoneFlag", false);
				example.createCriteria().andCustNameEqualTo(axdCustInfo.getCustName());
				List<AxdCustLoan> list2 = axdCustLoanService.list(example);
				if(list2.size()<1){
					model.addAttribute("nameFlag", false);
				}
			}else{
				model.addAttribute("axdCustLoan",list1.get(0));
			}
		}else{
			model.addAttribute("axdCustLoan",list.get(0));
		}
		model.addAttribute("axdCustInfo", axdCustInfo);
		return "/banks/manage/custinfo/check";
	}
	
	@RequestMapping(value="/checkUpdate",method=RequestMethod.POST)
	@Token(remove=true)
	public void checkUpdate(AxdCustInfo axdCustInfo,HttpServletResponse response,HttpServletRequest request){
		int update = axdCustInfoService.updateById(axdCustInfo);
		if(update>0){
			/*SysWxuser sysWxuser = sysWxuserService.selectByWxid(wxId);
			String token = sysWxTokenService.getAccessToken(sysWxuser);
			//TODO
			String basePath = getWechartBankUrl(request);
			StringBuffer sb=new StringBuffer(basePath);
			String text ="您的信息审核成功，请点击<a href='http://www.baidu.com'>上传凭证</a>";
			// 给当前人发送文本消息
			Map<String, Object> jsonMap = new HashMap<String, Object>();
			jsonMap.put("touser", axdCustInfo.getOpenid());
			jsonMap.put("msgtype", "text");
			Map<String, Object> textMap = new HashMap<String, Object>();
			textMap.put("content", text);
			jsonMap.put("text", textMap);
			String customMsgSendUrl = String.format(WxApi.CUSTOM_SEND, token);
			try {
				String resultStr = HttpUtils.postHttpByJsonData(customMsgSendUrl, JSON.toJSONString(jsonMap));
				if (logger.isInfoEnabled()) {
					logger.info("发送客服消息结果是：" + resultStr);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}*/
			CustInfoMsg custInfoMsg=new CustInfoMsg();
			custInfoMsg.setAxdCustInfo(axdCustInfo);
			if(axdCustInfo.getExamineStatus().equals("1")){
				custInfoMsg.setUrl(getWechartBankUrl(request)+"/anon/upload/index");
			}
			if(axdCustInfo.getExamineStatus().equals("2")){
				custInfoMsg.setUrl(getWechartBankUrl(request)+"/anon/cust/tobind");
			}
			custInfoMsg.setMsgType(BankServiceMsgEnum.TYPE_LOAN_YH.getValue());
			List<String> olist=new ArrayList<String>();
			olist.add(axdCustInfo.getOpenid());
			if(!axdCustInfo.getExamineStatus().equals("3")){
				executeSend(custInfoMsg,olist,wxId);
			}
		}
		writeHtml(response, "<script type='text/javascript'>window.parent.closeWin('"+update+"')</script>");
	}
	
	//查询网点信息
	@RequestMapping("ins")
	public void institutionsInfo(String keyword, HttpServletRequest request,HttpServletResponse response){
		if(!StringUtils.isEmpty(keyword)){
			/*HttpSession session = request.getSession();
			SysUser sysUser = (SysUser) session.getAttribute(sessionUserKey);
			Integer orgId = sysUser.getOrgId();
			AxdOrgInfo axdOrgInfo = axdOrgInfoService.findOneById(orgId);*/
			AxdOrgInfoExample example = new AxdOrgInfoExample();
			/*if(axdOrgInfo.getOrgLevel()==2){
				example.createCriteria().andPcodeEqualTo(axdOrgInfo.getOrgCode());
			}*/
			example.createCriteria().andOrgNameLike("%"+keyword+"%");
			List<AxdOrgInfo> list = this.axdOrgInfoService.list(example);
			List<OrgInfoVO> insList = new ArrayList<>(list.size());
			for(AxdOrgInfo bean : list){
				OrgInfoVO vo = new OrgInfoVO();
				vo.setCode(bean.getOrgCode());
				vo.setName(bean.getOrgName());
				insList.add(vo);
			}
			String json = JSON.toJSONString(insList);
			writeJson(response,json);
		}else{
			writeJson(response,"");
		}
	}
	
	
	private String getWechartBankUrl(HttpServletRequest request) {
		String weChartBankUrl = "http://" + request.getServerName();
		if (request.getServerPort() > 0 && request.getServerPort() != 80) {
			weChartBankUrl = weChartBankUrl + ":" + request.getServerPort();
		}
		weChartBankUrl += request.getContextPath(); // 项目名称

		return weChartBankUrl;
	}
	
	
	//发送模板消息
	private String executeSend(CustInfoMsg entity, List<String> openids, String wxid) {
		//取得access_token
		SysWxuser sysWxuser = sysWxuserService.selectByWxid(wxId);
		String token = sysWxTokenService.getAccessToken(sysWxuser);
		//取得发送消息模板所需数据
		MessageTemplate mt = msgHandler(entity);
		//取得发送地址
		String url = getTemplateUrl(token);
		//开启线程群发消息
		new Thread(new Runnable() {
			@Override
			public void run() {
				sendTplMsg(url, openids, mt,wxid);
			}
		}).start();;
		return null;
	}
	
	private MessageTemplate msgHandler(CustInfoMsg entity){
		MessageTemplate mtmp = new MessageTemplate();
		mtmp.setService_id(entity.getAxdCustInfo().getCustInfoId());
		WxTemplatePush tp = getTemplateByTemplateNo(TemplateEnum.loan_apply.getValue());
		String headColor = tp.getHeadColor();
		String contentColor = tp.getContentColor();
		String templateid = tp.getTemplateid();
		LoanApplyMessage ms = new LoanApplyMessage();
		
		ms.setFirst(getContent("尊敬的用户，您好！您在我行申请了贷款业务，审核信息如下:" + "\n",headColor));
		ms.setKeyword1(getContent(entity.getAxdCustInfo().getCustName()+"\n", contentColor));
		ms.setKeyword2(getContent(entity.getAxdCustInfo().getCustPhone()+"\n", contentColor));
		ms.setKeyword3(getContent(DateUtils.formatDatetime(entity.getAxdCustInfo().getCreateTime())+"\n", contentColor));
		ms.setKeyword4(getContent(entity.getAxdCustInfo().getExamineStatus().equals("1")?"通过":"不通过"+"\n", contentColor));
		if(entity.getAxdCustInfo().getExamineStatus().equals("1")){
			ms.setRemark(getContent("请点击详情！"+"\n", contentColor));
		}
		if(entity.getAxdCustInfo().getExamineStatus().equals("2")){
			ms.setRemark(getContent("原因:"+entity.getAxdCustInfo().getCheckNode()+"\n", contentColor));
		}
		//消息名称、类型
		mtmp.setService_name(BankServiceMsgEnum.TYPE_LOAN_YH.getKey());
		mtmp.setService_type(BankServiceMsgEnum.TYPE_LOAN_YH.getValue());
		
		mtmp.setData(ms);
		mtmp.setTemplate_id(templateid);
		if(entity.getUrl()!=null && !entity.getUrl().isEmpty()){
			mtmp.setUrl(entity.getUrl());
		}
		return mtmp;
	}
	
	private WxTemplatePush getTemplateByTemplateNo(String templateNo){
		WxTemplatePush templatePush = wxTemplatePushService.findByTemplateNo(templateNo);
		if(templatePush==null){
			throw new NullPointerException("templateNo:"+templateNo+",模版数据不存在");
		}
		return templatePush;
	}
	
	public Content getContent(String value, String color){
		Content ct = new Content();
		ct.setValue(value);
		ct.setColor(color);
		return ct;
	}
	
	public String getTemplateUrl(String accessToken){
		return String.format(WxApi.SEND_TEMPLATE, accessToken);
	}
	
	public void sendTplMsg(String url,List<String> openids,MessageTemplate mt,String wxid){
		Gson gson = new Gson();
		if(openids!=null&&openids.size()>0){
			//发送消息，封装对象
			for (String openid : openids) {
				try{
					if(openid==null || openid.isEmpty()){
						continue;
					}
					mt.setTouser(openid);
					String request = HttpClientUtil.httpPostRequest(url, gson.toJson(mt));
					logger.info("发送模板消息："+request);
					if(org.apache.commons.lang.StringUtils.isNotBlank(request)){
						JSONObject jsonObject = JSONObject.fromObject(request);
						if(jsonObject != null && jsonObject.get("errcode")!=null){
							if(jsonObject.getInt("errcode") == 0){//成功
								logger.info(openid + "发送模板消息成功!!!");
							}else{//失败
								logger.info(openid + "发送模板消息失败!!!");
							}
							
						}
					}
				}catch(Exception e){
					logger.error("发送模板消息失败：openid="+openid+"data="+JsonUtil.toJSONString(mt));
					e.printStackTrace();
				}
			}
		}
	}
}
